package server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
 * @author srh
 * @date 2020/10/18
 **/
public class NettyServer {

    public static void main(String[] args) throws InterruptedException {
        // 创建 NioEventLoop 的两大实例（bossGroup, workerGroup）
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        // 创建服务启动辅助类：组装一些必要的组件
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        // 设置组，bossGroup 负责连接，workerGroup 负责处理IO
        serverBootstrap.group(bossGroup, workerGroup)
                // 指定服务端监听的通道类型
                .channel(NioServerSocketChannel.class)
                // 设置channel handler，监听客户端连接后的处理
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        // 获取传输通道
                        ChannelPipeline pipeline = nioSocketChannel.pipeline();
                        // 在通道上添加对应的处理器|监听器
                        pipeline.addLast(new StringEncoder());
                        pipeline.addLast(new StringDecoder());
                        // 监听器队列上添加我们自己的处理方式
                        pipeline.addLast(new SimpleChannelInboundHandler<String>() {
                            @Override
                            protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
                                System.out.println("in@SimpleChannelInboundHandler message = " + s);
                            }
                        });
                    }
                });
        // 绑定监听端口
        ChannelFuture future = serverBootstrap.bind(8000).sync();
        System.out.println("start@ChannelFuture has success");

        // 等待服务器的channel管理，阻塞状态
        future.channel().closeFuture().sync();
    }
}
